const Redis = require('ioredis')

let redisConnectList = {}

class RedisUtils {
  static getRedisConnect (doc, db, callback) {
    let client = redisConnectList[doc._id]
    if (client === undefined) {
      client = new Redis({
        port: doc.port,
        host: doc.host,
        password: doc.password,
        db: 0,
        lazyConnect: true,
        connectTimeout: 3000
      })
      redisConnectList[doc._id] = client
      return callback(client)
    } else {
      client = redisConnectList[doc._id]
      return callback(client)
    }
  }

  static testConnect (doc, callback) {
    let client = new Redis({
      port: doc.port,
      host: doc.url,
      password: doc.password,
      db: 0,
      lazyConnect: true,
      connectTimeout: 3000
    })
    // eslint-disable-next-line handle-callback-err
    client.connect((err, result) => {
      client.disconnect()
      // eslint-disable-next-line standard/no-callback-literal
      return callback(true)
    })
  }
}

export default RedisUtils
